var channelHasData = false;
var trIndex = 0; // 表格唯一标识
var submitList = []; // 合作信息集合
var SPECIAL_SERVICE_PROVIDER_CODE = 10; // 服务类型 - 专项服务商 code
var ENABLING_SERVICE_PROVIDER_CODE = 20; // 服务类型 - 赋能服务商 code

document.addEventListener('saveSaleAreasEvent',(event) => {
	var selectSaleAreas = event.detail.saleAreas;
	var key = sessionStorage.getItem('saleAreaKey');
	submitList.forEach((item) => {
		if (item.key == key) {
			item.saleAreas = selectSaleAreas;
		}
	})
	renderFormTable(submitList);
}, false);

if (window.location.pathname.indexOf("commonDetailPage") > -1) {
	$(".next-step").remove();
	$(".last-step").remove();
	$(".cancleEditBtn").show();
	// renderDetail();//详情信息渲染
} else {
	$(".cancleEditBtn").remove();
	addCustomerFn();
}
if (thisProviderId && thisProviderId != "") {
	renderDetail(); //详情信息渲染
}

function matchNumber(el) {
	el.value = el.value.match(/\d+(\.\d{0,2})?/) ? el.value.match(/\d+(\.\d{0,2})?/)[0] : '';
}

function validateInp(el, msg) {
	if (msg) {
		if (el.value == "") {
			// $.Huimodalalert(msg,2000);
		}
	} else {
		if (el.value <= 0) {
			$.Huimodalalert("服务费率不可为0或小于0", 2000);
			el.value = "";
		} else if (el.value > 100) {
			$.Huimodalalert("服务费率需小于100", 2000);
			el.value = "";
		}
	}
}

/*获取合作渠道信息*/
function getChannelListFn(el, type, key) {
	if (type && type == "inp") {
		$(el).attr({
			"data-number": "",
			"data-id": ""
		});
		$(el).parents("tr").find(".customerName").val("").attr("data-id", "");
	}
	var params = {
		"name": el.value
	}
	web.doAjax(root.approvedServiceProviders.findChannelFromDockListByName, 'post', params, function (data) {
		if (data.code == "0") {
			$(".channelList").hide();
			$(el).parent().find(".channelList").css("display", "block");
			var channelHtml = '';
			if (!data.data || data.data.length == 0) {
				channelHtml = '<li class="clearfix pl-10 mb-5">无数据</li>';
			} else {
				data.data.forEach((item) => {
					channelHtml += "<li class='clearfix pl-10 mb-5' onclick='selectChannelItem(this," + JSON.stringify(item) + "," + JSON.stringify(key) + ")'>" + item.channelName + "</li>"
				})
			}
			$(el).parent().find(".channelList").html(channelHtml);
		}
	}, 2);
}
// 选择渠道
function selectChannelItem(el, data, key) {
	$(el).parent('ul').parent('div').parent('td').next('td').find('div .multiple-select-customer').empty();
	submitList.forEach((item) => {
		if (item.key == key) {
			item.customerList = [];
		}
	})
	$(el).parents("tr").find(".channelName").val(data.channelName).attr({
		"data-number": data.channelNumber,
		// "data-id": data.channelId
		"data-id": data.channelNumber
	});
	submitList.forEach(function(item) {
		if (item.key == key) {
			item.channelName = data.channelName;
			item.channelNumber = data.channelNumber;
			item.channelId = data.channelId;
		}
	})
	$(el).parents("tr").find(".channelList").hide();
}

// 获取合作客户信息
function getCustomerListFn(el, type, key) {
	if(!type) {
		$(el).next('div').children('input').val('');
	}
	if (!$(el).parents("tr").find(".channelName").attr("data-number")) {
		$.Huimodalalert("请先选择合作渠道", 2000);
		return;
	}
	var params = {
		"providerNumber": $(el).parents("tr").find(".channelName").attr("data-number"),
		"name": el.value
	}
	web.doAjax(root.approvedServiceProviders.findCustomerFromDockListByNameAndProviderNumber, 'post', params, function (data) {
		if (data.code == "0") {
			$(el).parent().find(".mul-dialog").css("display", "block");
			var customerHtml = '';
			if (!data.data || data.data.length == 0) {
				customerHtml = '<li class="clearfix pl-10 mb-5">无数据</li>';
			} else {
				var currentSubmitData = submitList.filter(function(item){
					return item.key == key
				})
				data.data.forEach((item) => {
					var isSelectArr = currentSubmitData[0].customerList && currentSubmitData[0].customerList.filter((ele) => (item.customerNumber == ele.customerNumber));
					var isSelect = isSelectArr && isSelectArr.length != 0 ? 'select-background' : '';
					customerHtml += "<li class='clearfix pl-10 mb-5' style='margin: 10px'>" +
								"<span class='li-span-item "+isSelect+"' onclick='selectCustomerItem(this," + JSON.stringify(item) + "," + JSON.stringify(key) + ")'>" + item.customerName + "</span>" +
							"</li>"
				})
			}
			$(el).parent().find(".customerList").html(customerHtml);
		}
	}, 2);
}

// 选择客户选项
function selectCustomerItem(el, data, key) {
	var $multipleSelectCustomer = $(el).parents("tr").find(".multiple-select-customer");
	if ($(el).hasClass('select-background')) {
		submitList.forEach(function(item) {
			if (item.key == key) {
				item.customerList = item.customerList.filter((i) =>  (i.customerNumber != data.customerNumber))
			}
		})
	} else {
		submitList.forEach(function(item) {
			if (item.key == key) {
				if (!item.customerList) {
					item.customerList = [];
				}
				item.customerList.push(data)
			}
		})
	}
	$(el).toggleClass('select-background');
	appendCustomerSpan($multipleSelectCustomer, getRowCustomerListByKey(key, submitList));
}


// 获取详情信息
function renderDetail() {
	var getCooperationDetail = getCooperationDetailPro(thisProviderId);
	getCooperationDetail.then(
		(res) => {
			if (res.length != 0) {
				channelHasData = true;
				submitList = res;
				submitList.forEach(function(item) {
					item.key = item.id;
				})
				renderFormTable(submitList);
			} else {
				channelHasData = false;
			}
		},
		(err) => {
			console.log(err);
		});
}
// 渲染表格
function renderFormTable(data) {
	var isDetail = window.location.pathname.indexOf("commonDetailPage") > -1
	var cooperationHtml = "";
	data.forEach((item, index) => {
		var disabledText =  isDetail && !item.isNew ? 'disabled' : '';
		// var selfDisable =  isDetail && !item.isNew ? 'self-disable' : '';
		var displayText = isDetail && !item.isNew ? 'none' : 'block';
		var specialSerSelect = item.providerType == SPECIAL_SERVICE_PROVIDER_CODE ? 'selected' : '';
		var enablingSerSelect = item.providerType == ENABLING_SERVICE_PROVIDER_CODE ? 'selected' : '';
		cooperationHtml += '<tr class="text-c" data-index='+index+'>\n' +
		'        <td>\n' +
		'            <div className="formControls" style="width: 300px;margin: auto;">'+
					"<input autocomplete='off' oninput='getChannelListFn(this,\"inp\","+JSON.stringify(item.key)+")' onfocus='getChannelListFn(this,"+null+"," + JSON.stringify(item.key) + ")' onblur='validateInp(this,\"请输入合作渠道\")' class='input-text radius ml-10 w-300 h-26 channelName' type='text' name='channelName' placeholder='合作渠道' data-id='" + item.channelId +"' data-number='"+ item.channelNumber +"' value='"+ item.channelName +"' "+disabledText+" />" +
		'            <ul class="w-300 ml-10 radius channelList relation select-list-box" style="display: none;">\n' +
		'            </ul></div>\n' +
		'        </td>\n' +
		'        <td>\n' +
					'<div class="formControls" style="width: 300px;margin: auto;">' +
						"<div data-key="+item.key+" class='multiple-select-customer' onclick='getCustomerListFn(this,"+null+"," + JSON.stringify(item.key) + ")'>"+renderCustomerSpan(item)+"</div>" +
						'<div class="mul-dialog" style="display: none;">' +
							"<input class='relation ml-10 w-300 h-26 customerName input-text radius' type='text' autocomplete='off' name='customerName' oninput='getCustomerListFn(this,\"inp\","+JSON.stringify(item.key)+")' onblur='validateInp(this,'请输入合作客户')'>\n" +
							'<ul class="w-300 ml-10 radius customerList relation select-list-box">\n' +
							'</ul>' +
						'</div>' +
					'</div>' +
		'        </td>\n' +
		'        <td>\n' +
					"<input onkeyup='reteInputHandler(this,"+JSON.stringify(item.key)+")' onpaste='matchNumber(this)' onblur='validateInp(this)' oninput='this.value=this.value.replace(/[^0-9.]/g,\"\")' onafterpaste='this.value=this.value.replace(/[^0-9.]/g,\"\")' class='input-text radius ml-10 w-100 rate' type='text' name='rate' autocomplete='off' value='" + dealNull(item.rate) + "' placeholder='服务费率' >%\n" +
		'        </td>\n' +
		'        <td>\n' +
					"<select placeholder='服务类型' onchange='serviceTypeChangeHandler(this,"+JSON.stringify(item.key)+")' class='select radius f-l service-type-select' name='serviceType' size='1'>" +
						"<option value=''>请选择</option>" +
						"<option value='"+SPECIAL_SERVICE_PROVIDER_CODE+"' "+specialSerSelect+">专项服务商</option>" +
						"<option value='"+ENABLING_SERVICE_PROVIDER_CODE+"' "+enablingSerSelect+">赋能服务商</option>" +
					"</select>" +
		'        </td>\n' +
				"<td>"+
					"<div>"+formatSaleAreas(item.saleAreas)+"</div>"+
					"<div><a onclick='showSaleAreasDialog(this, " + JSON.stringify(item.key) + ")'>设置区域</a></div>"+
				"</td>\n" +
				"<td><a style='display: "+displayText+"' onclick='deleteCooperationFn(this, " + JSON.stringify(item.key) + ")'>删除</a></td>\n" +
		'    </tr>';
	});

	$("#cooperation-table tbody").html(cooperationHtml);

	$('#cooperation-table').delegate('.icon-close', 'click', function (event) {
		var $multipleSelectCustomer = $(this).parent('span').parent('.multiple-select-customer');
		var $parentSpan = $(this).parent('span');
		var currentKey = $multipleSelectCustomer.attr('data-key');
		var currCustomerNumber = $parentSpan.attr('data-cusNum');
		submitList.forEach(function(item){
			if(item.key == currentKey){
				item.customerList = item.customerList.filter((i) =>  (i.customerNumber != currCustomerNumber))
			}
		})
		appendCustomerSpan($multipleSelectCustomer, getRowCustomerListByKey(currentKey, submitList));
		event.stopPropagation();
	});

	$('#cooperation-table').delegate('.multiple-select-customer .customer-item-span', 'click', function (event) {
		event.stopPropagation();
	});
}

// 渲染客户已选项
function renderCustomerSpan(data) {
	if (data.customerList && data.customerList.length > 0) {
		var customerSpanHtml = '';
		data.customerList.forEach((item) => {
			customerSpanHtml += '<span data-cusNum=' + item.customerNumber +
				' class="customer-item-span"><span>' + item.customerName +
				'</span>' + '<i class="icon-close"></i>' + '</span>'
		})
		return customerSpanHtml;
	}
	return '';
}
// 删除可编辑项
function deleteCooperationFn(el, key) {
	$(el).parents("tr")[0].remove();
	submitList = submitList.filter((item) => (item.key != key))
}

function appendCustomerSpan(ele, data) {
	var customerSpanHtml = '';
	data && data.forEach((item) => {
		customerSpanHtml += '<span data-cusNum=' + item.customerNumber +
			' class="customer-item-span"><span>' + item.customerName +
			'</span>' + '<i class="icon-close"></i>' + '</span>'
	})
	$(ele).html(customerSpanHtml);
}

function getRowCustomerListByKey(key, data) {
	var filterData = data.filter(item => item.key == key);
	if (filterData.length > 0 && filterData[0].customerList) {
		return filterData[0].customerList;
	}
}

// 服务费率获取
function reteInputHandler (el, key) {
	var $rateVal = $(el).val();
	if ($rateVal > 100 || $rateVal <= 0) {
		$rateVal = '';
	}
	updateSubmitList(key, 'rate', $rateVal)
}

// 服务类型获取
function serviceTypeChangeHandler(el, key) {
	updateSubmitList(key, 'providerType', $(el).val())
}

function updateSubmitList(key,fileName,val) {
	submitList.forEach((item) => {
		if (item.key == key) {
			item[fileName] = val
		}
	})
}

/*添加客户*/
function addCustomerFn() {
	var userName = JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name;
	trIndex+=1
	submitList.push({
		key:`NEW_TEMP_ID_${trIndex}`,
		createUserName: userName || '',
		updateUserName: userName || '',
		providerId: thisProviderId || '',
		channelName: '',
		channelId: '',
		channelNumber: '',
		rate: '',
		customerList: [
			// {customerName:'', customerNumber: ''},
		],
		// 服务类型
		providerType: '',
		// 服务区域
		saleAreas:[],
		isNew: true
	})
	renderFormTable(submitList);
}

function showSaleAreasDialog(el, key) {
	sessionStorage.setItem('saleAreaKey', key);
	var currentSaleAreas = submitList.filter((item) => ( item.key == key ))[0];
	if (currentSaleAreas && currentSaleAreas.saleAreas && currentSaleAreas.saleAreas.length > 0) {
		sessionStorage.setItem('saleAreas', JSON.stringify(currentSaleAreas.saleAreas));
	} else {
		sessionStorage.setItem('saleAreas', null);
	}
	layer_show("设置区域", "../../serviceProvider/appointArea.html","500","400","300","200")
}

/*保存合作信息*/
function saveCooperationInfo(stepFn) {
	var repeatChannelList = [];
	var channelNumberArr = submitList.map((item) => {
		return item.channelNumber;
	})
	channelNumberArr.forEach((item, index, arr) => {
		var bool = arr.indexOf(item,index+1);
		if ( bool != -1 ) {
			repeatChannelList.push(item);
		}
	})
	if (repeatChannelList.length != 0) {
		return $.Huimodalalert('合作渠道不能重复',2000);
	}
	if (submitList.length == 0) {
		return $.Huimodalalert("请新增客户信息", 2000);
	}
	var passTag = true;
	submitList.forEach((item) => {
		if(!item.channelNumber){
			passTag = false;
			return $.Huimodalalert("请选择合作渠道", 2000);
		}
		if(!item.customerList || item.customerList.length == 0){
			passTag = false;
			return $.Huimodalalert("请选择合作客户", 2000);
		}
		if(!item.rate){
			passTag = false;
			return $.Huimodalalert("请输入服务费率", 2000);
		}
		if(!item.providerType){
			passTag = false;
			return $.Huimodalalert("请选择服务类型", 2000);
		}
		if(!item.saleAreas || item.saleAreas.length == 0){
			passTag = false;
			return $.Huimodalalert("请选择服务区域", 2000);
		}
	})

	var params = submitList.map((item) => ({...item}));

	params.forEach((item) => {
		delete item.isNew
		delete item.key
	})

	if (!passTag) {
		return false;
	}

	if (window.location.pathname.indexOf("commonDetailPage") > -1 || channelHasData) {
		var doUrl = root.approvedServiceProviders.batchUpdateProviderCooperation;
	} else {
		var doUrl = root.approvedServiceProviders.batchAddProviderCooperation;
	}

	web.doAjax(doUrl, 'post', params, function (data) {
		if (data.code == 0) {
			$.Huimodalalert("操作成功", 2000);
			channelHasData = true;
			if (window.location.pathname.indexOf("commonDetailPage") > -1) {
				$(".form-box").load("detailPackage/cooperationInfoDetail.html");
			}
			if (stepFn) {
				eval(stepFn)
			}
		} else {
			$.Huimodalalert(data.msg, 2000);
		}
	}, 1);
}

$(document).bind("click", function (e) {
	//id为menu的是菜单，id为open的是打开菜单的按钮
	if ($(e.target).closest(".channelList").length == 0 && $(e.target).closest(".channelName").length == 0) {
		//点击id为menu之外且id不是不是open，则触发
		$(".channelList").hide();
	}
	if ($(e.target).closest(".customerList").length == 0 && $(e.target).closest(".customerName").length == 0) {
		$(".mul-dialog").hide();
	}
});
// 格式化设置区域
function formatSaleAreas(saleAreas) {
    var areaHtml = '';
    saleAreas && saleAreas.forEach((item) => {
        if (item.code == 0) {
            areaHtml += '<div class="customer-item">'+
                '<span>'+item.name+'</span>'+
            '</div>'
        } else {
            areaHtml += '<div class="customer-item">'+
                '<span>'+item.name+'</span> '+
                "<a onclick='showDialog("+JSON.stringify(item.children)+")'>("+item.children.length+")</a>"
            +'</div>'
        }
    })
    return areaHtml;
}
// 区域弹框
function showDialog (data) {
    var str = '';
    data.forEach((item) => {
        str += '<span>'+item.name+'</span> '
    })
    layer.alert(str, {title:'服务区域',offset:'c'})
}
